<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Controller\BaseController;
use App\Model\AdminHasPermission;
use App\Model\AdminPermission;
use App\Request\Admin\AdminPermissionRequest;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\RefreshTokenMiddleware;

/**
 * @AutoController()
 * @Middleware(RefreshTokenMiddleware::class)
 */
class PermissionsController extends BaseController
{
    public function lists()
    {
        $all = AdminPermission::all()->toArray();

        $data = AdminPermission::where(function ($query)use ($all){
            $query->where('pid',$this->request->input('default_id'));
        })->get()->map(function ($item,$key)use ($all){

            $temp = $item;

            foreach ($all as $k => $v){
                if ($v['pid'] == $temp['id']){
                    $temp['hasChildren'] = true;
                    break;
                }
            }
            return $temp;
        });

        return $this->success(['items' => $data]);
    }

    public function store(AdminPermissionRequest $request)
    {
        $p = ['name','remark','pid','type','path'];

        AdminPermission::create($request->inputs($p));

        return  $this->message('添加成功');
    }

    public function update(AdminPermissionRequest $request)
    {
        $p = ['name','remark','pid','type','path'];
        AdminPermission::where('id',$request->input('id'))->update($request->inputs($p));

        return  $this->message('编辑成功');
    }

    public function destroy()
    {
        $id = $this->request->input('id');
        if (AdminPermission::where('pid',$id)->first()){
            return $this->failed('该节点下有子节点,不能删除');
        }

        AdminPermission::where('id',$id)->delete();

        AdminHasPermission::where('permission_id',$id)->delete();

        return  $this->message('删除成功');
    }

}
